var draco_document_width = 1024;
var draco_document_height = 768;
$(function() {
	// 处理jquery portlet
	$(".jqportlet").addClass(
			"ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
			.find(".jqportlet-header").addClass(
					"ui-widget-header ui-corner-all").prepend(
					'<span class="ui-icon ui-icon-minusthick cursor"></span>')
			.end().find(".jqportlet-content");

	$(".jqportlet-header .ui-icon").click(
			function() {
				$(this).toggleClass("ui-icon-minusthick").toggleClass(
						"ui-icon-plusthick");
				$(this).parents(".jqportlet:first").find(".jqportlet-content")
						.toggle();
			});

	// 处理portlet
	var portlet_header = $(".portlet").find(".portlet-header");
	var portlet_tool = $("<div class=\"portlet-tool\"></div>").appendTo(
			portlet_header);
	if ($(".portlet").hasClass("collapsible"))
		$("<div class=\"portlet-tool-collapse\"></div>").appendTo(portlet_tool)
				.bind("click", portlet_collapse);
	if ($(".portlet").hasClass("closable"))
		$("<div class=\"portlet-tool-close\"></div>").appendTo(portlet_tool)
				.bind("click", portlet_close);
	// 处理resulttable
	$(".resulttable")
			.find(".resulttable-body>tr:odd")
			.addClass("resulttable-row-alt")
			.end()
			.find(".resulttable-body>tr:last td")
			.addClass("nobottomborder")
			.end()
			.find(".resulttable-body>tr")
			.mouseenter(function() {
				$(this).addClass("resulttable-row-over");
			})
			.mouseleave(function() {
				$(this).removeClass("resulttable-row-over");
			})
			.click(
					function(event) {
						if ($(this).find("input[type=radio]").size() > 0) {
							$(this).find("input[type=radio]").attr("checked",
									true);
							$(".resulttable-body>tr").removeClass(
									"resulttable-row-selected");
							$(this).addClass("resulttable-row-selected");
						} else if ($(this).find("input[type=checkbox]").size() > 0) {
							if (event.target.type !== 'checkbox') {
								$(':checkbox', this).trigger('click');
							}// 很奇怪，修改checkbox的状态必须用这个方式，如果直接attr，checkbox本身就click不了
							if ($(this).find("input[type=checkbox]").attr(
									"checked"))
								$(this).addClass("resulttable-row-selected");
							else
								$(this).removeClass("resulttable-row-selected");
						}
					}).dblclick(
					function(event) {
						var alink = $(this).find('td:last a');
						if (alink[0] != undefined)
							open($(alink).attr('href'),
									$(alink).attr('target') != '' ? $(alink)
											.attr('target') : '_self');
					});
	
	if ($("form[method=post]").find('input[type=text]').size() == 1)
	{
		//由于form中如果仅仅含一个文本框的话，按回车它会自动提交，而不走input type=submit，这样校验就没辙了。
		//所以如果检测到有一个文本框，则默认加多一个，同时display:none
		$('<input type="text" style="display:none"/>').insertBefore($("form").find('input[type=text]:first'));
	}
	
	// 防止重复提交
	$("form").submit(function() {
		$(":submit", this).attr("disabled", "disabled");
	});
	/*window.onbeforeunload = function(){
		$(":submit", $("form")).attr("disabled", "disabled");
	};*/
	
	//让checkbox选中时加背景色，注意checkbox中的文字必须用span装载
	$('input[type=checkbox]').click(function(event){
		if ($(this).attr("checked"))
			$('+span',this).addClass("cbhighlight");
		else
			$('+span',this).removeClass("cbhighlight");
		});
});
function portlet_collapse() {
	if ($(this).hasClass("portlet-tool-expand")) {
		$(this).removeClass("portlet-tool-expand");
		$(this).addClass("portlet-tool-collapse");
		$(this).parents(".portlet:first").find(".portlet-content").slideDown(
				"slow");
	} else {
		$(this).removeClass("portlet-tool-collapse");
		$(this).addClass("portlet-tool-expand");
		$(this).parents(".portlet:first").find(".portlet-content").slideUp(
				"slow");
	}
	return false;
}
function portlet_close() {
	$(this).parents(".portlet:first").remove();
	return false;
}
/* 透明div显示框，用于显示正在检索请稍候等 */
function DivAlert(messageDiv) {
	this.messageDIV = messageDiv;
	// 创建提示框底层
	this.bottomDIV = document.createElement("div");
	// 获取body中间点
	var x = ($(window).width() > window.screen.width) ? window.screen.width / 2
			: $(window).width() / 2, y = ($(window).height() > window.screen.height) ? window.screen.height / 2
			: $(window).height() / 2;
	// 配置样式
	this.bottomDIV.style.cssText = "background-color:#CCCCCC;height:"
			+ $(window).height()
			+ "px;opacity:0.30;filter:Alpha(opacity=30);-moz-opacity:.30;width:100%;margin-top:0px;margin-left:0px;position:absolute;top:0px;left:0px;zIndex:100;";
	// 遮盖select
	this.bottomDIV.innerHTML = "<iframe frameborder=\"0\" style=\"position:absolute; visibility:inherit; top:0px; left:0px; width:100%; height:"
			+ $(window).height()
			+ "px; z-index:-1; -ms-filter:'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';\"></iframe>";
	// 禁用回车和tab键
	this.bottomDIV.innerHTML = this.bottomDIV.innerHTML
			+ "<!--<script>document.onkeydown=function(){return false;}</script><script event=\"onkeydown\" for=\"document\">return false;</script>-->";
	// 显示提示框
	this.show = function() {
		// 显示提示框底层
		document.body.appendChild(this.bottomDIV);
		// 显示messageDIV
		document.body.appendChild(this.messageDIV);
		// 把messageDIV定位到body中间
		this.messageDIV.style.position = "absolute";
		x = x - this.messageDIV.clientWidth / 2;
		y = y - this.messageDIV.clientHeight / 2;
		this.messageDIV.style.top = y + "px";
		this.messageDIV.style.left = x + "px";
		this.messageDIV.style.zIndex = 101;
	}
	// 移除提示框
	this.remove = function() {
		try {
			document.body.removeChild(this.messageDIV);
			document.body.removeChild(this.bottomDIV);
		} catch (e) {

		}
	}
}
/* 创建正在检索，请稍候div */
/* loadingTxt为显示信息 */
function createLoadingDiv(loadingTxt) {
	var dc;
	var d = document.createElement("div");
	d.style.cssText = "border:1px solid #f87600;width:220px;height:60px;line-height:60px;background-color:#ffffff;padding:10px;text-align:center;vertical-align:middle";
	// 向提示框内容部分画需要显示的信息
	d.innerHTML = '<div style=\"margin-top:0px!important;margin-top:50px;\"><span class="loading-icon"></span>&nbsp;<span style=\"color:#f87600;\">' + loadingTxt + '</span><div>';
	// 实例化提示框
	dc = new DivAlert(d);
	// 显示提示框
	dc.show();
	return dc;
}

/* 检查email格式 */
function common_checkEmail(email) {
	if (email == undefined)
		return true;
	if ($.trim(email).length == 0)
		return true;
	var mails = new Array();
	mails = $.trim(email).split(";");
	var testv = false;
	for(mailCount = 0; mailCount<mails.length; mailCount++){
		if($.trim(mails[mailCount]).length > 0)
			testv = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mails[mailCount]);
		else testv = true;
		if(testv == false)
			return false;
	}
	return true;
}
/* 检查是否是实数 */
function common_checkFloat(objvalue) {
	if (objvalue == undefined)
		return true;
	return /^(\+|-)?\d+($|\.\d+$)/.test(objvalue);
}
function common_checkUnsignedInteger(objvalue) {
	if (objvalue == undefined)
		return true;
	return /^\d+$/.test(objvalue);
}
function common_checkInteger(objvalue){
	if (objvalue == undefined)
		return true;
	return /^-?\d+$/.test(objvalue);
}
/*检查日期的格式是否是yyyy-MM-dd*/
function common_checkDate(objvalue){
	var reg = /^(\d{4})-(\d{2})-(\d{2})$/; 
	var r = objvalue.match(reg); 
	if(r==null)return false; 
	r[2]=r[2]-1;
	var d= new Date(r[1],r[2],r[3]); 
	if(d.getFullYear()!=r[1])return false; 
	if(d.getMonth()!=r[2])return false; 
	if(d.getDate()!=r[3])return false;  
	return true; 
}
/* 检查是否为四位年份 */
function common_checkYear(objvalue) {
	return /^[1-9](\d){3}$/.test(objvalue);
}

/*为实数加入三位的分组，用,分隔*/
function formatNumber(num){   
	if(!/^(\+|-)?(\d+)(\.\d+)?$/.test(num)){return   num;}      
	var   a   =   RegExp.$1,   b   =   RegExp.$2,   c   =   RegExp.$3;      
	var   re   =   new   RegExp().compile("(\\d)(\\d{3})(,|$)");      
	while(re.test(b))   b   =   b.replace(re,"$1,$2$3");      
	return a +""+ b +""+ c;      
} 

/* 添加html代码到制定位置 */
if (typeof HTMLElement != "undefined"
		&& !HTMLElement.prototype.insertAdjacentElement) {
	HTMLElement.prototype.insertAdjacentElement = function(where, parsedNode) {
		switch (where) {
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode, this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode, this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling)
				this.parentNode.insertBefore(parsedNode, this.nextSibling);
			else
				this.parentNode.appendChild(parsedNode);
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function(where, htmlStr) {
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where, parsedHTML);
	}

	HTMLElement.prototype.insertAdjacentText = function(where, txtStr) {
		var parsedText = document.createTextNode(txtStr);
		this.insertAdjacentElement(where, parsedText);
	}
}

function toTXT(str){
    var RexStr = /\<|\>|\"|\'|\&/g
    str = str.replace(RexStr,
        function(MatchStr){
            switch(MatchStr){
                case "<":
                    return "&lt;";
                    break;
                case ">":
                    return "&gt;";
                    break;
                case "\"":
                    return "&quot;";
                    break;
                case "'":
                    return "&apos;";
                    break;
                case "&":
                    return "&amp;";
                    break;
            }
        }
    )
    return str;
}

var selectAddDialogStack = new Array();
var idForSelectAddDialogStack = new Array();

/**
 * 为下拉框的新增界面获取宽度
 * @return
 */
function getWidthForSelectAdd()
{
	var arr = window.top.selectAddDialogStack;
	return window.top.draco_document_width - 100 - arr.length*20;
}

/**
 * 为下拉框的新增界面获取高度
 * @return
 */
function getHeightForSelectAdd()
{
	var arr = window.top.selectAddDialogStack;
	return window.top.draco_document_height - 100 - arr.length*20;
}

/**
 * 为下拉框增加新增按钮
 * @param addLink 新增的指向
 * @param selectname 下拉框名
 * @param datasource 下拉框数据源
 * @param datatextfield 下拉框的内容字段
 * @param datavaluefield 下拉框的值字段
 * @param obj 新增按钮对象
 * @return
 */
function addInHome(selectname,datasource,datatextfield,datavaluefield,obj,contextpath,myrefreshfunc)
{
	var addLink = $(obj).attr("link");
	//先在最顶级页面加入div和iframe
	var tmpid = new Date().getTime();
	var dialog_html = '<div id="' + tmpid + 'Div" style="display:none" class="templateSelectAddDialog">';
	dialog_html = dialog_html + '<iframe id="' + tmpid + 'Frame" frameborder="0" width="100%" height="98%"></iframe>';
	dialog_html = dialog_html + '</div>';
	$(dialog_html).appendTo($(window.top.document.body));
	//预设dialog
	$('#' + tmpid + 'Div',window.top.document).dialog({
  		bgiframe: true,
		autoOpen: false,
		modal: true,
		width:getWidthForSelectAdd(),//window.screen.width-30,
		height:getHeightForSelectAdd(),//window.screen.height,
		close:function(){
			$('#' + tmpid + 'Frame',window.top.document).remove();
			$('#' + tmpid + 'Div',window.top.document).remove();
			window.top.selectAddDialogStack.pop();
			//关闭时刷新对应的下拉框
			//判断是否有自己的刷新函数，如果有则执行自己的刷新函数
			if (myrefreshfunc)
			{
				myrefreshfunc();
			}
			else
			{
				window.top.refreshForAddInHome(selectname,datasource,datatextfield,datavaluefield,$(obj).prevAll('select').val(),contextpath,$(obj).prevAll('select'));
			}
		},
		title:'新窗口' + window.top.selectAddDialogStack.length
  	});
  	//增加随机参数
  	if (addLink.indexOf('?rd=') < 0 || addLink.indexOf('&rd=') < 0)
  	{
	  	if (addLink.indexOf('?') > 0)
		  	addLink = addLink + '&rd=' + Math.random();
	  	else
	  		addLink = addLink + '?rd=' + Math.random();
  	}
  	//打开dialog
	$('#' + tmpid + 'Frame',window.top.document).attr({src:addLink});
	$('#' + tmpid + 'Div',window.top.document).dialog('open');
	window.top.selectAddDialogStack.push(tmpid);
}

/**
 * 提供关闭当前dialog的函数，其中id为新增成功后返回的id
 * @param id
 * @return
 */
function closeSelectAddDialog(id)
{
	if (id)
		window.top.idForSelectAddDialogStack.push(id);
	var arr = window.top.selectAddDialogStack;
	if (arr.length > 0)
	{
		var tmpid = arr[arr.length-1];
		$('#' + tmpid + 'Div',window.top.document).dialog('close');
	}
}

/**
 * 刷新obj对应的下拉框
 * @param selectname 下拉框名
 * @param datasource 下拉框数据源
 * @param datatextfield 下拉框的内容字段
 * @param datavaluefield 下拉框的值字段
 * @return
 */
function refreshForAddInHome(selectname,datasource,datatextfield,datavaluefield,ovalue,contextpath,obj)
{
	var url = contextpath + "/template/RefreshSelectTemplate.action";
	$.post(url, {"sn":selectname,"ds":datasource,"dvf":datavaluefield,"dtf":datatextfield,"ov":ovalue,"rd":Math.random()},
			   function(data){
			   	$(obj).html(data);
	});
}

function pointeraddInHome(addLink,thispointer)
{
	var pointer_left = thispointer.parent.pointerinfoDialog_left;
	var pointer_top = thispointer.parent.pointerinfoDialog_top;
	//先在最顶级页面加入div和iframe
	var tmpid = new Date().getTime();
	var dialog_html = '<div id="' + tmpid + 'Div" style="display:none" class="templatePointerAddDialog">';
	dialog_html = dialog_html + '<iframe id="' + tmpid + 'Frame" frameborder="0" width="100%" height="98%"></iframe>';
	dialog_html = dialog_html + '</div>';
	$(dialog_html).appendTo($(window.top.document.body));
	//预设dialog
	$('#' + tmpid + 'Div',window.top.document).dialog({
  		bgiframe: true,
		autoOpen: false,
		modal: true,
		width:getWidthForSelectAdd(),//window.screen.width-30,
		height:getHeightForSelectAdd(),//window.screen.height,
		position:'center',//[pointer_left,pointer_top],
		close:function(){
			$('#' + tmpid + 'Frame',window.top.document).remove();
			$('#' + tmpid + 'Div',window.top.document).remove();
			window.top.selectAddDialogStack.pop();
			var id = window.top.idForSelectAddDialogStack.pop();
			//此id为新增后的id
			//回掉pointer页的自定义函数refreshpointer(id)
			if (thispointer.refreshpointer)
				thispointer.refreshpointer(id);
			//thispointer.document.location.reload(true);
		},
		title:'新窗口' + window.top.selectAddDialogStack.length
  	});
  	//增加随机参数
  	if (addLink.indexOf('?rd=') < 0 || addLink.indexOf('&rd=') < 0)
  	{
	  	if (addLink.indexOf('?') > 0)
		  	addLink = addLink + '&rd=' + Math.random();
	  	else
	  		addLink = addLink + '?rd=' + Math.random();
  	}
  	//打开dialog
	$('#' + tmpid + 'Frame',window.top.document).attr({src:addLink});
	$('#' + tmpid + 'Div',window.top.document).dialog('open');
	window.top.selectAddDialogStack.push(tmpid);
}

function genIDForOpenDialogOutside()
{
	//为了在最外层做弹出框产生个代表的id
	var tmpid = new Date().getTime();
	return 't'+tmpid;
}
function choosePOp(chooseLink){
	var tmpid = window.top.genIDForOpenDialogOutside();
	var chooseOKFunctionName = tmpid + "chooseEROK";
	window.top.openDialogOutside(tmpid,
			{
				openLink:chooseLink,
				dialogtitle:'<s:text name="Page.EResource.ERChoose.Title"/>',
				dialogwidth:800,
				dialogheight:500
			});
}

var openDialogOutsideFromWindowOKFuncStack = new Array();

/**
 * 为pointer在打开dialog时跳到最外层
 * @param tmpid 所产生的代表id
 * @param dialogparam dialog的参数：openLink 需要打开的连接 
 * 									dialogtitle dialog的title 
 * 									dialogwidth 宽 
 * 									dialogheight 高
 * @param chooseOKFunction 需要在最外层增加的函数名（tmpid+内层处理函数名）
 * @param fromwindowOkFunction 内层的确定 处理函数
 * @return
 */
function openDialogOutside(tmpid,dialogparam,chooseOKFunction,fromwindowOkFunction)
{
	var openLink = dialogparam.openLink;
	var dialogtitle = dialogparam.dialogtitle;
	var dialogwidth = dialogparam.dialogwidth;
	var dialogheight = dialogparam.dialogheight;
	var dialog_html = '<div id="' + tmpid + 'Div" style="display:none" class="openOutsideDialog">';
	dialog_html = dialog_html + '<iframe id="' + tmpid + 'Frame" frameborder="0" width="100%" height="98%"></iframe>';
	if(chooseOKFunction)
	{
		dialog_html = dialog_html + '<script type="text/javascript">';
		dialog_html = dialog_html + 'function ' + chooseOKFunction + '(){';
		dialog_html = dialog_html + 'if (window.top.openDialogOutsideFromWindowOKFuncStack.length > 0){var fromwindowOkFunc = window.top.openDialogOutsideFromWindowOKFuncStack[window.top.openDialogOutsideFromWindowOKFuncStack.length-1];fromwindowOkFunc.apply(this,arguments);}'
		dialog_html = dialog_html + '$(\'#' + tmpid + 'Div\').dialog(\'close\');';
		dialog_html = dialog_html + '}';
		dialog_html = dialog_html + '</script>';
	}
	dialog_html = dialog_html + '</div>';
	
	$(dialog_html).appendTo($(window.top.document.body));
	//预设dialog
	$('#' + tmpid + 'Div',window.top.document).dialog({
  		bgiframe: true,
		autoOpen: false,
		modal: true,
		width:dialogwidth,
		height:dialogheight,
		close:function(){
			$('#' + tmpid + 'Frame',window.top.document).remove();
			$('#' + tmpid + 'Div',window.top.document).remove();
			window.top.openDialogOutsideFromWindowOKFuncStack.pop();
		},
		title:dialogtitle
  	});
	//增加随机参数
  	if (openLink.indexOf('?rd=') < 0 || openLink.indexOf('&rd=') < 0)
  	{
	  	if (openLink.indexOf('?') > 0)
	  		openLink = openLink + '&rd=' + Math.random();
	  	else
	  		openLink = openLink + '?rd=' + Math.random();
  	}
  	//打开dialog
	$('#' + tmpid + 'Frame',window.top.document).attr({src:openLink});
	$('#' + tmpid + 'Div',window.top.document).dialog('open');
	window.top.openDialogOutsideFromWindowOKFuncStack.push(fromwindowOkFunction);
}

function publicCheckExists(formid,type,contextPath,tname,fname,fid,idtype)
{
	var checkresult = false;
	var handleLink = contextPath+'/CheckExistsClass/checkexists.action';
	var thisname = $('#' + formid).find('input[name='+tname+'.'+fname+']:first').val();
	if(type=='add')
	{
		$.ajax({url:handleLink,
				async:false,
				type:"POST",
				dataType:"json", 
				data:{"checkExistsClass.thisname": thisname,"checkExistsClass.fieldname": fname,"checkExistsClass.tablename": tname,"rd":Math.random()},
				success:function(data){
				     if (data.success)
				     {
				    	 checkresult = data.result;
				     }
				     else
				     {
				    	 jError(data.error,'<s:text name="Page.Alert.Info"/>');
				    	 checkresult = true;
				     }
				   }});
	}else{
		var thisid = $('#' + formid).find('input[name='+tname+'.'+fid+']:first').val();
		$.ajax({url:handleLink,
				async:false,
				type:"POST",
				dataType:"json", 
				data:{"checkExistsClass.thisid":thisid,"checkExistsClass.thisname": thisname,"checkExistsClass.fieldname": fname,"checkExistsClass.fieldid": fid,"checkExistsClass.tablename": tname,"checkExistsClass.idtype": idtype,"rd":Math.random()},
				success:function(data){
				     if (data.success)
				     {
				    	 checkresult = data.result;
				     }
				     else
				     {
				    	 jError(data.error,'<s:text name="Page.Alert.Info"/>');
				    	 checkresult = true;
				     }
				   }});
	}
	return checkresult; 
}
function SetCwinHeight(fobj)
{
    var bobo=document.getElementById(fobj); //iframe id
    if (document.getElementById)
    {
       if (bobo && !window.opera)
       {
            if (bobo.contentDocument && bobo.contentDocument.body.offsetHeight)
            {
             bobo.height = bobo.contentDocument.body.offsetHeight;
            }
            else 
            if(bobo.Document && bobo.Document.body.scrollHeight)
            {
             bobo.height = bobo.Document.body.scrollHeight;
            }
       }
    }
}
function parameterMerge(path,classname,entityname,idname,idtype)
{
	window.location.href = path+'/ParameterMerge/listParameter.action?thisclassname='+classname+'&thisentityname='+entityname+'&idname='+idname+'&idtype='+idtype;
}

$(document).ready(function(){
    //改变表头
    $(".portlet-header").append("<div class='portlet-header-right' style='z-index:0'></div>");
});